package com.zjw.contorller;


import cn.hutool.core.util.StrUtil;
import com.zjw.domain.dto.LoginRegisterUserDto;
import com.zjw.domain.vo.ResponseResult;
import com.zjw.exception.SystemException;
import com.zjw.service.UserService;
import com.zjw.system.SystemReturnEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/login")
    public ResponseResult login(@RequestBody LoginRegisterUserDto user) {
//        判断数据完整性
        if (StrUtil.isBlank(user.getUsername())
                || StrUtil.isBlank(user.getPassword())
                || StrUtil.isBlank(user.getKey())
                || StrUtil.isBlank(user.getCaptchaCode()))
            throw new SystemException(SystemReturnEnum.DATA_INCOMPLETE);


//        后门如果验证码为77777直接通过
        if (user.getCaptchaCode().equals("77777"))
            return userService.login(user.getUsername(), user.getPassword());

//        判断验证码是否正确
        String resCode = redisTemplate.opsForValue().get(user.getKey());
        if ((StrUtil.isEmpty(resCode) || !resCode.equals(user.getCaptchaCode().toLowerCase()))) {
            throw new SystemException(SystemReturnEnum.CAPTCHA_ERROR);
        }


//        执行到这里证明验证码正确需要从库中移除
        redisTemplate.delete(user.getKey());
        return userService.login(user.getUsername(), user.getPassword());
    }


    @PutMapping("/register")
    private ResponseResult register(@RequestBody LoginRegisterUserDto user){
//        判断数据完整性
        if (StrUtil.isBlank(user.getUsername())
                || StrUtil.isBlank(user.getPassword())
                || StrUtil.isBlank(user.getKey())
                || StrUtil.isBlank(user.getCaptchaCode())) {
            throw new SystemException(SystemReturnEnum.DATA_INCOMPLETE);
        }


//        后门如果验证码为77777直接通过
        if (user.getCaptchaCode().equals("77777"))
            return userService.register(user);


//        判断验证码是否正确
        String resCode = redisTemplate.opsForValue().get(user.getKey());
        if ((StrUtil.isEmpty(resCode) || !resCode.equals(user.getCaptchaCode().toLowerCase()))) {
            throw new SystemException(SystemReturnEnum.CAPTCHA_ERROR);
        }


//        执行到这里证明验证码正确需要从库中移除
        redisTemplate.delete(user.getKey());

        return userService.register(user);
    }

}
